class Kvue extends EventTarget {
    constructor(options) {
        super()
        this.$options = options
        this.compile()
        this.observe(this.$options.data)
    }
    observe(data){
        console.log("observe")
        let keys = Object.keys(data)
        keys.forEach(key => {
            this.defineReactive(data, key, data[key])
        })
    }
    defineReactive(data, key, value){
        let _this = this;
        Object.defineProperty(data,key,{
            configurable: true,
            enumerable: true,
            get(){
                console.log("get...");
                return value;
            },
            set(newValue){
                let event = new CustomEvent(key,{
                    detail: newValue
                });
                _this.dispatchEvent(event)
                value = newValue;
            }
        })
    }
    compile(){
        let el = document.querySelector(this.$options.el)
        this.compileNode(el);
    }
    compileNode(el){
        let childNodes = el.childNodes;
        childNodes.forEach(node => {
            // nodeType:  1: element, 3: text
            if(node.nodeType === 1){
                let attrs = node.attributes;
                console.log(attrs);
                [...attrs].forEach(attr => {
                    let attrName = attr.name;
                    let attrValue = attr.value;
                    if(attrName.indexOf("v-")===0){
                        attrName = attrName.substr(2)
                        if(attrName==="html"){
                            node.innerHTML = this.$options.data[attrValue]
                        } else if(attrName==="model"){
                            node.value = this.$options.data[attrValue];
                            node.addEventListener("input",e=>{
                                this.$options.data[attrValue] = e.target.value
                            })
                        }
                    }
                })
                    if(node.childNodes.length>0){
                        this.compileNode(node)
                    }
            }else if(node.nodeType === 3){
                let reg = /\{\{(.*)\}\}/
                let textContent = node.textContent;
                if(reg.test(textContent)){
                    // console.log('存在花括号')
                    // console.log(RegExp.$1, 'textContent')
                    let $1 = RegExp.$1;
                    node.textContent = node.textContent.replace(reg, this.$options.data[$1])
                    console.log(this,'this')
                    this.addEventListener($1,e=>{
                       let oldValue = this.$options.data[$1];
                       let reg = new RegExp(oldValue)
                       node.textContent = node.textContent.replace(reg, e.detail)
                    })
                }
            }
        })
    }
}